package com.zhenbeiju.udp.udp;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ToggleButton;

import org.w3c.dom.Text;

import java.net.DatagramPacket;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import commanutil.utl.net.UdpClient;
import commanutil.view.DialogInfo;

public class MainActivity extends AppCompatActivity {

    @Bind(R.id.editText)
    EditText editText;
    @Bind(R.id.editText2)
    EditText editText2;
    @Bind(R.id.toggleButton)
    ToggleButton toggleButton;
    @Bind(R.id.recycler)
    RecyclerView recycler;
    @Bind(R.id.send)
    Button send;
    @Bind(R.id.content)
    EditText content;
    @Bind(R.id.ishex)
    Button ishex;

    private UdpClient client;
    private boolean isHexMode;
    private List<DatagramPacket> recValues = new ArrayList<>();
    private UdpClient.udpOngetData udpOngetData;
    private LayoutInflater inflater;
    private MyAdapter myAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        this.inflater = getLayoutInflater();
        myAdapter = new MyAdapter();
        recycler.setLayoutManager(new LinearLayoutManager(getBaseContext(), LinearLayoutManager.VERTICAL, false));
        recycler.setAdapter(myAdapter);
    }


    @OnClick(R.id.toggleButton)
    public void onConnectClick() {
        try {
            int port = Integer.valueOf(editText2.getText().toString());
            if (client == null) {
                client = UdpClient.getInstance(port, MyApplication.mBaseContext);
                udpOngetData = new UdpClient.udpOngetData() {
                    @Override
                    public void ongetdata(final DatagramPacket receivePacket) {
                        recValues.add(receivePacket);
                        MyApplication.mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                myAdapter.notifyDataSetChanged();
                                recycler.scrollToPosition(recValues.size() - 1);
                            }
                        });

                    }
                };
                client.addonGetData(udpOngetData);
                toggleButton.setChecked(true);
            } else {
                client.removeonGetData(udpOngetData);
                client = null;
                toggleButton.setChecked(false);
            }
        } catch (Exception e) {
            DialogInfo.showToast("error");
        }

    }


    @OnClick(R.id.send)
    public void onSendClick() {
        String ip = editText.getText().toString();
        int port = Integer.valueOf(editText2.getText().toString());
        String contentValue = content.getText().toString();
        if (client != null) {
            client.send(contentValue.getBytes(), ip, port);
        }
    }


    private class MyAdapter extends RecyclerView.Adapter<ViewHolder> {
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = inflater.inflate(R.layout.udp_item, parent, false);
            ViewHolder holder = new ViewHolder(view);
            return holder;
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            holder.bindData(position);
        }

        @Override
        public int getItemCount() {
            return recValues.size();
        }
    }


    private class ViewHolder extends RecyclerView.ViewHolder {
        TextView content;
        TextView ip;
        View view;

        public ViewHolder(View itemView) {
            super(itemView);
            content = (TextView) itemView.findViewById(R.id.textView);
            ip = (TextView) itemView.findViewById(R.id.textView2);
            view = itemView;
        }

        public void bindData(int postion) {
            if(postion%2 ==0){
                view.setBackgroundColor(0xffdddddd);
            }else{
                view.setBackgroundColor(0xffffffff);
            }
            DatagramPacket datagramPacket = recValues.get(postion);
            content.setText(new String(cleanbytes(datagramPacket.getData())));
            ip.setText(datagramPacket.getAddress().getHostAddress());

        }
    }

    public static byte[] cleanbytes(byte[] bytes) {
        int length = bytes.length;
        int i = length - 1;
        for (; i > 0; i--) {
            if (bytes[i] != 0) {
                i++;
                break;
            }
        }

        byte[] newbytes = new byte[i];
        System.arraycopy(bytes, 0, newbytes, 0, i);
        return newbytes;
    }

}
